package com.ai.suno;

/**
 * @author: heJinQin
 * @create: 2024-04-25 02:01
 * @description:
 **/


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;

public class Main {
    public static void main(String[] args) throws IOException {
        String URL = "https://cdn1.suno.ai/ce614987-ba1a-46e5-9764-35f6e7ed5b79.mp4";
        String[] split = URL.split("\\.");
        InputStream inputStream = getInputStream(URL);
        if (inputStream != null) {
            boolean createResult = creatFile("loadCookie",split[split.length-1]);
            if (createResult) {
                String path = "C:\\Users\\14550\\Desktop\\2024\\suno\\" + "loadCookie.mp4";
                writeToLocal(path, inputStream);
            }
        }
    }



    /**
     * @return
     * @throws IOException
     * @Title: getInputStream
     * @Description: TODO 获取网络连接的InputStream
     * @CreateDate:2021 Nov 2 20:56:56
     */
    public static InputStream getInputStream(String uri) throws IOException {
        InputStream inputStream = null;
        HttpURLConnection httpurlconn = null;
        try {
            URL url = new URL(uri);
            if (url != null) {
                httpurlconn = (HttpURLConnection) url.openConnection();
                //设置连接超时时间
                httpurlconn.setConnectTimeout(10000);
                //表示使用GET方式请求
                httpurlconn.setRequestMethod("GET");
                int responsecode = httpurlconn.getResponseCode();
                if (responsecode == 200) {
                    //从服务返回一个输入流
                    inputStream = httpurlconn.getInputStream();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 将InputStream写入本地文件
     *
     * @param destination 写入本地目录
     * @param input       输入流
     * @throws IOException
     */
    private static void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }

    /**
     * 创建文件
     *
     * @param fileName
     * @return
     */
    public static boolean creatFile(String fileName,String fileType) throws IOException {
        try {
            File tempFile = File.createTempFile(fileName, fileType);
            tempFile.createNewFile();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}


